/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs;

import com.thoughtworks.xstream.XStream;
import org.digitalsoul.switchplugin.SwitchPlugin;
import org.digitalsoul.switchplugin.patterns.NamedCompoundPattern;
import org.eclipse.jface.preference.IPreferenceStore;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


public class Preferences {

    private static final String SWITCH_PATTERNS_KEY = "switch.patterns";

    public static void savePatterns(Collection<NamedCompoundPattern> patterns) {
        getStore().setValue(SWITCH_PATTERNS_KEY, encodePatterns(patterns));
    }
    
    public static Collection<NamedCompoundPattern> loadPatterns() {
        return decodePatterns(getStore().getString(SWITCH_PATTERNS_KEY));
    }
    
    public static IPreferenceStore getStore() {
        return SwitchPlugin.getDefault().getPreferenceStore();    
    }
    
    protected static String encodePatterns(Collection<NamedCompoundPattern> patterns) {
        XStream xstream = new XStream();
        return xstream.toXML(patterns);
    }

    public static List<NamedCompoundPattern> decodePatterns(String xml) {
        XStream xstream = new XStream();
        List<NamedCompoundPattern> patterns = getDefaults();
        try {
            Object loadedObj = xstream.fromXML(xml);
            if (loadedObj instanceof List) {
                patterns = (List<NamedCompoundPattern>) loadedObj;
            }
        }
        catch (Exception e) {
            //e.printStackTrace();
        }
        return patterns; 
    }

    public static void setupDefaults() {       
        getStore().setDefault(SWITCH_PATTERNS_KEY, encodePatterns(getDefaults())); 
    }

    public static List<NamedCompoundPattern> getDefaults() {
        List<NamedCompoundPattern> patterns = new ArrayList<NamedCompoundPattern>();
        for (int i = 1; i <= 3; i++) {
            patterns.add(new NamedCompoundPattern("Pattern " + i));
        }
        return patterns;
    }
}